﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Fast.Authorization
{
    /// <summary>
    /// 授权策略提供程序
    /// </summary>
    [SkipScan]
    internal sealed class FastAuthorizationPolicyProvider : IAuthorizationPolicyProvider
    {
        /// <summary>
        /// 默认授权策略提供程序，当备份策略提供来使用
        /// </summary>
        private DefaultAuthorizationPolicyProvider BackupPolicyProvider { get; }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="options"></param>
        /// <exception cref="System.NullReferenceException"></exception>
        public FastAuthorizationPolicyProvider(IOptions<AuthorizationOptions> options)
        {
            BackupPolicyProvider = new DefaultAuthorizationPolicyProvider(options);
        }

        /// <summary>
        /// 返回默认授权策略 ([Authorize] 未指定) 策略的属性所使用的策略
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.NullReferenceException"></exception>
        public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
        {
            return BackupPolicyProvider.GetDefaultPolicyAsync();
        }

        /// <summary>
        /// 当未指定策略时， GetFallbackPolicyAsync将返回授权中间件所使用的策略 (后备授权策略) 。
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.NullReferenceException"></exception>
        public Task<AuthorizationPolicy> GetFallbackPolicyAsync()
        {
            return BackupPolicyProvider.GetFallbackPolicyAsync();
        }

        /// <summary>
        /// 返回给定名称的授权策略
        /// </summary>
        /// <param name="policyName"></param>
        /// <returns></returns>
        /// <exception cref="System.NullReferenceException"></exception>
        public Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
        {
            var policies = policyName.Split(',', StringSplitOptions.RemoveEmptyEntries)
                .Where(p => p.StartsWith(PolicyConst.AuthorizePrefix))
                .Select(p => p.Substring(PolicyConst.AuthorizePrefix.Length))
                .ToArray();
            if (policies.Any())
            {
                var policy = new AuthorizationPolicyBuilder();
                policy.AddRequirements(new FastAuthorizationRequirement(policies));
                return Task.FromResult(policy.Build());
            }

            return BackupPolicyProvider.GetPolicyAsync(policyName);
        }
    }
}
